package br.edu.utfpr.backupTools.view.telas.principal.tabela;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.border.SoftBevelBorder;

import br.edu.utfpr.backupTools.model.pojo.Backup;
import br.edu.utfpr.backupTools.util.backup.ZipUtil;
import br.edu.utfpr.backupTools.util.enums.Acao;
import br.edu.utfpr.backupTools.util.enums.TipoConexao;
import br.edu.utfpr.backupTools.util.worker.ProgressDialogTask;
import br.edu.utfpr.backupTools.util.worker.WorkerBackup;
import br.edu.utfpr.backupTools.util.worker.WorkerRestore;
import br.edu.utfpr.backupTools.view.action.backup.VerificaBackup;
import br.edu.utfpr.backupTools.view.action.strategy.Control;
import br.edu.utfpr.backupTools.view.telas.principal.JanelaPrincipal;
import br.edu.utfpr.comum.RetornoValidacao;

public class BackupCellComponent extends JPanel {
    Backup backup;
    JButton gerarButton, excluirButton, restoreButton;
    JLabel texto, descricao,data;
    JPanel botoes, dados;
    StringBuilder str;

    VerificaBackup actionRestore = new VerificaBackup();

    public BackupCellComponent(final JanelaPrincipal janelaPrincipal) {

        gerarButton = new JButton();
        gerarButton.setToolTipText("Gerar backup");
        gerarButton.setIcon(new javax.swing.ImageIcon(getClass().getClassLoader().getResource("images/Play-Normal-icon.png")));
        gerarButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String title = "Aguarde";
                String message = "Gerando backup " + backup.getDescricao();
                ProgressDialogTask pdt = new ProgressDialogTask(new JFrame(), title, message);
                WorkerBackup work = new WorkerBackup(backup);
                pdt.setModal(true);
                pdt.addTask(work);
                pdt.run();
                if (backup.getTipoConexao().equals(TipoConexao.REMOTA)) {
                    if (!work.getRv().isOk()) {
                        janelaPrincipal.showMessage(work.getRv().getErro(), JOptionPane.ERROR_MESSAGE);
                    } else {
                        janelaPrincipal.showMessage("Backup '" + backup.getDescricao() + "' gerado com sucesso no servidor", JOptionPane.INFORMATION_MESSAGE);
                    }
                    JanelaPrincipal.addLog(work.getRv().isOk() ? "Backup '" + backup.getDescricao() + "' gerado com sucesso no servidor" : work.getRv().getErro());
                } else {
                    if (!work.getRv().isOk()) {
                        janelaPrincipal.showMessage(work.getRv().getErro(), JOptionPane.ERROR_MESSAGE);
                    } else {
                        janelaPrincipal.showMessage("Backup '" + backup.getDescricao() + "' gerado com sucesso", JOptionPane.INFORMATION_MESSAGE);
                    }
                }

                janelaPrincipal.populaTabela();
                janelaPrincipal.updateSelecionado(null);
            }
        });

        excluirButton = new JButton();
        excluirButton.setToolTipText("Excluir");
        excluirButton.setIcon(new javax.swing.ImageIcon(getClass().getClassLoader().getResource("images/Trash-icon.png")));
        excluirButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int op = JOptionPane.showConfirmDialog(null, "Deseja excluir o backup " + backup.getDescricao(), "Excluir", JOptionPane.YES_NO_OPTION);
                if (op == 0) {
                    RetornoValidacao rv = Control.getInstance().command().get(Acao.EXCLUIR_BACKUP).execute(backup);
                    JanelaPrincipal.addLog(rv.isOk() ? "Backup " + backup.getDescricao() + " excluido com sucesso" : rv.getErro());
                    janelaPrincipal.populaTabela();
                    janelaPrincipal.updateSelecionado(null);
                }
            }
        });

        restoreButton = new JButton();
        restoreButton.setToolTipText("Fazer restore do backup");
        restoreButton.setIcon(new javax.swing.ImageIcon(getClass().getClassLoader().getResource("images/backup-restore-icon.png")));
        restoreButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {

                //verifica se tem backup gerado no servidor
                actionRestore.execute(backup);
                if (!actionRestore.isPossuiBackup()) {
                    janelaPrincipal.showMessage("Não existe backup gerado para: '" + backup.getDescricao() + "'", JOptionPane.WARNING_MESSAGE);
                    JanelaPrincipal.addLog("Não existe backup gerado para: '" + backup.getDescricao() + "'");
                    return;
                }

                //verifica se a pasta de origem ainda existe
                if (ZipUtil.diretorioExiste(backup)) {
                    int op = JOptionPane.showConfirmDialog(null, "A pasta de origem ainda existe, deseja substituir pelo restore?", "Atenção", JOptionPane.YES_NO_OPTION);

                    if (op != 0) {
                        return;
                    }

                    ZipUtil.deleteDiretorio(backup);
                }

                //inicia worker de geração do restore
                String title = "Aguarde";
                String message = "Gerando restore " + backup.getDescricao();
                ProgressDialogTask pdt = new ProgressDialogTask(new JFrame(), title, message);
                WorkerRestore work = new WorkerRestore(backup);
                pdt.setModal(true);
                pdt.addTask(work);
                pdt.run();

                RetornoValidacao rv = work.getRv();

                janelaPrincipal.showMessage(rv.isOk() ? "Restore executado com sucesso" : rv.getErro(), JOptionPane.INFORMATION_MESSAGE);

                if (rv.isOk())
                    JanelaPrincipal.addLog("Restore '" + backup.getDescricao() + "' executado com sucesso em: " + backup.getOrigem());
                else
                    JanelaPrincipal.addLog(rv.getErro());
            }
        });

        this.setLayout(new BorderLayout());
        setBorder(new SoftBevelBorder(SoftBevelBorder.LOWERED));
        Font f = new Font("Arial", Font.BOLD, 12);

        descricao = new JLabel();
        descricao.setFont(f);
        texto = new JLabel();
        data = new JLabel();

        dados = new JPanel();
        dados.setLayout(new BorderLayout());
        dados.add(texto,BorderLayout.WEST);
        dados.add(data,BorderLayout.CENTER);

        botoes = new JPanel();
        botoes.setLayout(new BorderLayout());
        botoes.add(gerarButton, BorderLayout.WEST);
        botoes.add(restoreButton, BorderLayout.CENTER);
        botoes.add(excluirButton, BorderLayout.EAST);

        add(descricao, BorderLayout.WEST);
        add(dados, BorderLayout.CENTER);
        add(botoes, BorderLayout.EAST);
    }

    public void updateData(Backup backup, boolean isSelected, JTable table) {
        this.backup = backup;
        descricao.setText(" Backup:    ");

        str = new StringBuilder();
        str.append(backup.getDescricao());

        //if(backup.getUltimaExecucao() != null){
            //SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
            //data.setText("       Última execução: "+format.format(backup.getUltimaExecucao()));
            //data.setForeground(Color.blue);
        //}
        //else{
           //data.setText("       Nenhum backup gerado");
           //data.setForeground(Color.red);
        //}

        texto.setText(str.toString());

        if (isSelected) {
            setBackground(new Color(214, 217, 223));
            dados.setBackground(new Color(214, 217, 223));
            botoes.setBackground(new Color(214, 217, 223));
        } else {
            setBackground(new Color(255, 255, 255));
            botoes.setBackground(new Color(255, 255, 255));
            dados.setBackground(new Color(255, 255, 255));
        }
    }


}